<style>
.image {
  width: 100%;
  display: block;
}
</style>
<template>
  <div id="suggest_approve">
    <!--工具条-->
    <div name="searchColums">
      <el-form :inline="true" :model="filters" size="small" ref="filters" class="searchForm">
        <el-form-item class="el-form-item" label="报修人" prop="liftUserName">
          <el-input class="filter-item" placeholder="报修人姓名" v-model="filters.liftUserName"></el-input>
        </el-form-item>
        <el-form-item class="el-form-item" label="报修时间" prop="startTimeBegin">
          <el-date-picker v-model="filters.startTimeBegin" type="date" value-format="yyyy-MM-dd"
                          placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item class="el-form-item" label="至" prop="startTimeEnd">
          <el-date-picker v-model="filters.startTimeEnd" type="date" value-format="yyyy-MM-dd"
                          placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item  label="状态">
          <el-select size="small" v-model="filters.status" clearable placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <span class="bth_search">
          <el-form-item>
            <el-button type="success" icon="el-icon-search" v-on:click="getDataGrid(true)">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" @click="resetSearchForm('filters')">重置</el-button>
          </el-form-item>
        </span>
      </el-form>
    </div>
    <!--toolbar-->
    <el-row id="toolbar_unit">
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <el-button type="success" size="mini" icon="el-icon-check" @click="handleAdd">新增</el-button>
          <el-button type="primary" size="mini" @click="handleFenpei" :disabled="this.sels.length===0"
                     icon="el-icon-upload">分配
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!--列表-->
    <el-table :data="gridDatas" id="dataGrid" empty-text=" " border stripe size="mini"
              :header-row-class-name="headStyle" highlight-current-row v-loading="listLoading"
              :row-class-name="tableRowClassName" @sort-change="handleSortChange" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column prop="index" :formatter="index_formatter" label="序号" width="60"></el-table-column>
      <el-table-column prop="liftUserName" label="报修人姓名" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="startTime" label="报修时间" width="140" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="问题描述" show-overflow-tooltip></el-table-column>
      <el-table-column label="图片" width="100">
        <template slot-scope="scope">
          <el-button round @click="showImgPath('repair', scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="repairUserName" label="维修人员" width="80" show-overflow-tooltip></el-table-column>
      <el-table-column prop="repairResultName" label="维修结果" width="80" show-overflow-tooltip></el-table-column>
      <el-table-column prop="resultImg" label="维修结果图片" width="140" show-overflow-tooltip>
      	<template slot-scope="scope">
          <el-button round @click="showImgPath('repair_result', scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="operationDescription" label="维修描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="statusName" label="报修状态" width="80" show-overflow-tooltip></el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar" id="pageDiv">
      <el-pagination small background @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total"
                     layout="total,sizes, prev, pager, next" style="float:right;"></el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm" size="mini">
        <el-col :span="24">
          <el-form-item label="问题描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="editForm.description" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传图片" prop="imgPath">
            <el-input v-model="addForm.imgPath" type="hidden" style="display: none!important;"></el-input>
            <el-upload class="upload-demo" action="/admin/repairRecord/upload" :on-preview="imgHandlePreview"
                       :on-remove="imgHandleRemove" :before-upload="beforeImgUpload" :file-list="imgList"
                       :data="uploadParams" list-type="picture">
              <el-button size="small" type="primary">上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" @close="handleAddBeforeClose" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm" size="small">
        <el-col :span="8">
          <el-form-item label="所属小区" prop="communityId">
            <el-select size="small" v-model="addForm.communityId" placeholder="请选择" @change="handleSelectBuilding">
              <el-option v-for="communitItem in communityOptions" :key="communitItem.id" :label="communitItem.name"
                         :value="communitItem.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="楼宇" prop="buildingId">
            <el-select size="small" v-model="addForm.buildingId" placeholder="请选择" @change="handleSelectUnit">
              <el-option v-for="(buildingItem,index) in buildingOptions" :key="index" :label="buildingItem.name"
                         :value="buildingItem.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单元" prop="unitId">
            <el-select size="small" v-model="addForm.unitId" placeholder="请选择" @change="handleSelectHouse">
              <el-option v-for="(unitItem,index) in unitOptions" :key="index" :label="unitItem.name"
                         :value="unitItem.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="房屋" prop="houseId">
            <el-select size="small" v-model="addForm.houseId" placeholder="请选择" @change="handleSelectUser">
              <el-option v-for="(houseItem,index) in houseOptions" :key="houseItem.id" :label="houseItem.houseName"
                         :value="houseItem.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="业主" prop="liftUser">
            <el-select size="small" v-model="addForm.liftUser" placeholder="请选择">
              <el-option v-for="item in liftUserOptions" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="问题描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="addForm.description"></el-input>
          </el-form-item>
        </el-col>
        <el-input v-model="addForm.id" type="hidden" style="display: none!important;"></el-input>
        <el-col :span="24">
          <el-form-item label="上传图片" prop="imgPath">
            <el-upload class="upload-demo" action="/admin/repairRecord/upload" :on-preview="imgHandlePreview"
                       :on-remove="imgHandleRemove" :before-upload="beforeImgUpload" :file-list="imgList"
                       :headers="uploadHeader" :data="uploadParams" :on-success="imgSuccess" list-type="picture">
              <el-button size="small" type="primary">上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传图片</div>
            </el-upload>
          </el-form-item>
        </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--图片查看界面-->
    <el-dialog title="报修图片" :visible.sync="imgFormVisible" :close-on-click-modal="false">
      <el-row>
        <el-col v-for="(imgPath,index) in imgListShow" :key="index">
          <el-card :body-style="{ padding: '0px' }">
            <img :src="imgPath.data" class="image"/>
          </el-card>

        </el-col>
      </el-row>
    </el-dialog>

    <!--维修人选择界面-->
    <el-dialog title="选择" :visible.sync="userSelectFormVisible" :close-on-click-modal="false">
      <el-tree :props="defaultProps" :load="loadChildrenNode" lazy highlight-current node-key="id"
               :expand-on-click-node="false" ref="tree" accordion @node-click="getNodeData">
      </el-tree>
    </el-dialog>

  </div>
</template>
<script>
  import {getToken, setToken, removeToken,getFileIp} from '@/util/auth'
  import {getUUID} from '@/util/util'
  import request from '@/router/axios'
export default {
  name: 'repairRegister',
  data() {
    return {
      statusOptions: [],
      communityOptions: [],
      buildingOptions: [],
      unitOptions: [],
      houseOptions: [],
      liftUserOptions: [
        {
          id: '',
          name: ''
        }
      ],
      //单元过滤条件
      filters: {
        liftUserName: '',
        startTimeBegin: '',
        startTimeEnd: '',
        status: ''
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      url: {
        //单元数据
        list: '/admin/repairRecord/page',
        save: '/admin/repairRecord/add',
        approve: '/admin/repairRecord/approve',
        submitSug: '/admin/repairRecord/fenpei'
      },
      gridDatas: [],
      suggestTypeOptions: [],
      sort: {
        sort: 'sort',
        order: 'asc'
      },
      total: 0,
      page: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],
      imgPaths: [],
      uploadParams: {type: 'repair', relationId: ''},
      imgList: [],
      imgListShow: [],
      editLoading: false,
      editFormVisible: false,
      addFormVisible: false,
      editForm: {},
      addForm: {
        id: undefined,
        buildingId: undefined,
        unitId: undefined,
        houseId: undefined,
        liftUser: undefined,
        description: undefined
      },
      editFormRules: {},
      addFormRules: {
        liftUser: [
          {
            required: true,
            message: '请选择业主 '
          }
        ],
        description: [
          {
            required: true,
            message: '请填写问题描述 '
          }
        ]
      },
      userSelectFormVisible: false,
      imgFormVisible: false,
      userSelectLoading: false,
      userSelectForm: {},
      uploadHeader: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    //初始化下拉框
    initData: function() {
      request.get('/admin/community?getCommunitysByUserId').then(res => {
        if (res.status === 200) {
          this.communityOptions = res.data
        }
      })
      request.get('/admin/dict/type/repair_status').then(res => {
        if (res.status === 200) {
          this.statusOptions = res.data
        }
      })
    },
    handleAddBeforeClose() {
      this.$refs.addForm.resetFields()
    },
    handleSelectBuilding() {
      this.addForm.buildingId = ''
      this.addForm.unitId = ''
      this.addForm.houseId = ''
      this.addForm.liftUser = ''
      request
        .get(
          '/admin/communityBuilding/getCommunityBuildings/' +
          this.addForm.communityId
        )
        .then(res => {
          if (res.status === 200) {
            this.buildingOptions = res.data
          }
        })
    },
    handleSelectUnit() {
      this.addForm.unitId = ''
      this.addForm.houseId = ''
      this.addForm.liftUser = ''
      request
        .get(
          '/admin/communityBuilding/getBuildingUnits/' + this.addForm.buildingId
        )
        .then(res => {
          if (res.status === 200) {
            // 判断楼宇下单元数据是否为空
            if (res.data.length === 0) {
              // 说明该楼宇下没有单元数据，直接去获取到房屋列表
              this.unitOptions = []
              request
                .get(
                  '/admin/unitHouse/getUnitHousesByBuildingId/' +
                  this.addForm.buildingId
                )
                .then(res => {
                  if (res.status === 200) {
                    this.houseOptions = res.data
                  }
                })
            } else {
              this.unitOptions = res.data
            }
          }
        })
    },
    handleSelectHouse() {
      this.addForm.houseId = ''
      this.addForm.liftUser = ''
      request
        .get('/admin/unitHouse/getUnitHouses/' + this.addForm.unitId)
        .then(res => {
          if (res.status === 200) {
            this.houseOptions = res.data
          }
        })
    },
    handleSelectUser() {
      this.addForm.liftUser = ''
      request
        .get('/admin/houseOwner/getHouseOwners/' + this.addForm.houseId)
        .then(res => {
          if (res.status === 200) {
            this.liftUserOptions = res.data
          }
        })
    },
    handleSortChange(sort) {
      this.sort = {
        sort: sort.prop,
        order: sort.order == 'ascending' ? 'asc' : 'desc'
      }
      this.getDataGrid()
    },
    tableRowClassName(row, index) {
      //把每一行的索引放进row
      row.index = row.rowIndex
    },
    headStyle({ row, rowIndex }) {
      return 'table_head_style'
    },
    index_formatter: function(row, column, cellValue, index) {
      //放回索引值
      return this.pageSize * (this.page - 1) + 1 + index
    },
    handleCurrentChange(val) {
      this.page = val
      this.getDataGrid()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.getDataGrid()
    },
    resetSearchForm(formName) {
      this.$refs.filters.resetFields()
    },
    selsChange: function(sels) {
      this.sels = sels
    },
    handleFenpei: function(index, row) {
      for (var i = 0; i < this.sels.length; i++) {
        if (this.sels[i].status != '1') {
          this.$message({
            message: '记录已派单。',
            type: 'info',
            duration: 1500
          })
          return
        }
      }
      this.userSelectFormVisible = true
    },
    //图片点击事件
    imgHandlePreview: function(file) {},
    //图片删除事件
    imgHandleRemove: function(file, fileList) {
      let para = {
        id: file.id
      }
      request
        .get('/admin/repairRecord/deleteImg', {
          params: para
        })
        .then(res => {
        })
    },
    //图片上传之前验证格式
    beforeImgUpload: function(file) {
      const type = file.type
      const flag =
        type == 'image/jpeg' ||
        type == 'image/gif' ||
        type == 'image/png' ||
        type == 'image/bmp'
      if (!flag) {
        this.$message.error('只支持上传图片!')
      }

      return flag
    },

    //图片上传成功后
    imgSuccess: function(response, file, fileList) {
      var fileId = response.obj
      for (var i = 0; i < fileList.length; i++) {
        if (file.uid == fileList[i].uid) {
          fileList[i].id = fileId
          break
        }
      }
    },
    showImgPath: function(type, row) {
      this.imgListShow = []
      let para = {id: row.id,type:type}
      request({
        url: '/admin/repairRecord/showImg',
        method: 'get',
        params: para
      }).then(res => {
        for (var i = 0; i < res.data.length; i++) {
          var img = {}
          img.id = res.data[i].id
          img.data = getFileIp() + res.data[i].data
          this.imgListShow.push(img)
        }
      })
      this.imgFormVisible = true
    },
    loadChildrenNode(node, resolve) {
      if (node.level === 0) {
        request.get('/admin/community?getCommunitysByCurrentUser').then(res => {
          if (res.status === 200) {
            return resolve(res.data)
          }
        })
      } else if (node.level === 1) {
        //点击小区节点，获取角色列表
        request
          .get('/admin/repairRecord/roleList/' + node.data.id)
          .then(res => {
            if (res.status === 200) {
              return resolve(res.data)
            }
          })
      } else if (node.level === 2) {
        //点击角色节点，获取角色下面所有用户
        request
          .get(
            '/admin/user/userList/' + node.data.id + '/' + node.parent.data.id
          )
          .then(res => {
            if (res.status === 200) {
              return resolve(res.data)
            }
          })
      } else {
        return resolve([])
      }
    },
    getNodeData(e, node, data) {
      if (node.level == 3) {
        // 获取到要分配的维修员的id
        var acceptUserId = e.userId
        var name = e.name
        var ids = this.sels.map(item => item.id).toString()
        this.$confirm('确认将选中的报修单指派给' + name + '吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            this.userSelectFormVisible = false
            this.listLoading = true
            let para = {
              userId: acceptUserId,
              repairStatus: '2',
              ids: ids
            }
            request
              .get('/admin/repairRecord/updateRepairStatus', {
                params: para
              })
              .then(res => {
                this.listLoading = false
                this.$message({
                  message: '指派成功',
                  type: 'success',
                  duration: 1500
                })
                this.getDataGrid()
              })
          })
          .catch(() => {
          })
      }
    },

    //新增
    handleAdd: function() {
      this.imgList = []
      var zj = getUUID()
      this.addForm.id = zj
      this.uploadParams.relationId = zj
      this.addFormVisible = true
      ;(this.buildingOptions = []),
        (this.unitOptions = []),
        (this.houseOptions = []),
        (this.liftUserOptions = [])
    },
    //编辑
    editSubmit: function() {
      this.$refs.editUnitForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editUnitLoading = true
            let para = Object.assign({}, this.editUnitForm)
            request.post(this.url.unitEdit, para).then(res => {
              this.editUnitLoading = false
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1500
              })
              this.$refs['editUnitForm'].resetFields()
              this.editUnitFormVisible = false
              this.getDataGrid()
            })
          })
        }
      })
    },
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            this.addForm.imgPath = this.imgPaths.toString()
            let param = Object.assign({}, this.addForm)
            request.post(this.url.save, param).then(res => {
              this.editLoading = false
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1500
              })
              this.$refs['addForm'].resetFields()
              this.addFormVisible = false
              this.getDataGrid()
            })
          })
        }
      })
    },

    //获取单元列表数据
    getDataGrid(flag) {
      //获取当前树节点选中小区
      if(flag){
      	this.page = 1;
      }
      let para = {
        params: {
          page: this.page,
          limit: this.pageSize,
          //排序
          orderByField: this.sort.sort,
          isAsc: this.sort.order,
          type: '0',
          liftUserName: this.filters.liftUserName,
          startTimeBegin: this.filters.startTimeBegin,
          startTimeEnd: this.filters.startTimeEnd,
          status: this.filters.status
        }
      }
      this.listLoading = true
      request.get(this.url.list, para).then(res => {
        this.total = res.data.total
        var datas = res.data.records
        this.gridDatas = datas
        this.listLoading = false
      })
    }
  },
  mounted() {
    this.getDataGrid()
    this.initData()
  }
}
</script>
